// 笔试强训day30:最长公共子序列(一)

// 二维数组
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n, m; cin >> n >> m;
    string str1, str2;
    cin >> str1 >> str2;
    vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= m; j++)
        {
            if(str1[i - 1] == str2[j - 1])
                dp[i][j] = dp[i - 1][j - 1] + 1;
            else
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
        }
    }
    cout << dp[n][m] << endl;
}


// 空间压缩，一维数组
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n, m; cin >> n >> m;
    string str1, str2;
    cin >> str1 >> str2;
    if(n < m)
    {
        swap(n, m);
        swap(str1, str2);
    }
    vector<int> dp(m + 1, 0);
    for(int i = 1; i <= n; i++)
    {
        int prev = 0;
        for(int j = 1; j <= m; j++)
        {
            int tmp = dp[j];
            if(str1[i - 1] == str2[j - 1])
                dp[j] = prev + 1;
            else
                dp[j] = max(dp[j], dp[j - 1]);
            prev = tmp;
        }
    }
    cout << dp[m] << endl;
}